package com.zimsoft.strato.admin.bundle.v1_0_0.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import com.strato.base.osgi.v1_0_0.BundleUtil;
import com.strato.mvc.annotation.v1_0_0.annotation.method.RequestMapping;
import com.strato.mvc.annotation.v1_0_0.annotation.type.Controller;
import com.strato.mvc.api.v1_0_0.model.ModelAndView;
import com.zimsoft.strato.admin.bundle.v1_0_0.comm.Activator;

@Controller
@com.strato.mvc.annotation.v1_0_0.annotation.type.RequestMapping("${strato.admin.url.prefix}")
public class BundleController {
	@RequestMapping("/bundle/bundleList")
	public ModelAndView bundleList(HttpServletRequest request,ModelAndView mav){
		Map<Object,Object> modelMap = new HashMap<Object,Object>();
		BundleContext context = Activator.getContext();
		Bundle[] bundles = context.getBundles();
		if(bundles !=null && bundles.length > 0){
			List<Map<String,Object>> bundleList = new ArrayList<Map<String,Object>>();
			for(Bundle bundle : bundles){
				Map<String,Object> bMap = new HashMap<String,Object>();
				bMap.put("bundleName", bundle.getSymbolicName());
				bMap.put("state", bundle.getState());
				bMap.put("version", bundle.getVersion());
				bundleList.add(bMap);
			}
			modelMap.put("bundleList", bundleList);
			mav.setModel(modelMap);
		}

		mav.setViewName("bundleList");
		return mav;
	}
	
	@RequestMapping("/bundle/serviceList")
	public ModelAndView serviceList(HttpServletRequest request,ModelAndView mav){
		String bundleName = request.getParameter("bundleName");
		Map<Object,Object> modelMap = new HashMap<Object,Object>();
		BundleContext context = Activator.getContext();
		
		Bundle bundle = BundleUtil.getBundle(bundleName, context);
		ServiceReference<?>[] srs = bundle.getRegisteredServices();
		if(srs !=null && srs.length > 0){
			List<List<Map<String,Object>>> bundleList = new ArrayList<List<Map<String,Object>>>();
			for(ServiceReference<?> sr : srs){
				String[] propKeys = sr.getPropertyKeys();
				Object service = context.getService(sr);
				if(propKeys == null || propKeys.length == 0){
					continue;
				}
				List<Map<String,Object>> propList = new ArrayList<Map<String,Object>>();
				for(String key : propKeys){
					Map<String,Object> bMap = new HashMap<String,Object>();
					bMap.put("key", key);
					Object val = sr.getProperty(key);
					if(val instanceof String[]){
						String[] vals = (String[])val;
						if(vals != null && vals.length > 0)
							bMap.put("value", vals[0]);
					}else{
						bMap.put("value", sr.getProperty(key));
					}
					propList.add(bMap);
				}
				
				bundleList.add(propList);
			}
			modelMap.put("serviceList", bundleList);
			mav.setModel(modelMap);
		}

		mav.setViewName("serviceList");
		return mav;
	}
}
